<template>
  <div class="list-container">
    <UserDialog
      v-model:visible="dialogVisible"
      :isEdit="dialogMode === 'edit'"
      :userId="editId"
      :userData="editData"
      @success="handleDialogSuccess"
    />

    <!-- 搜索和操作栏 -->
    <div class="list-header">
      <div class="search-form">
        <div class="search-form-item">
          <label>用户名</label>
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-form-item">
          <label>手机号</label>
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-form-item">
          <label>邮箱</label>
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter="handleSearch"
          />
        </div>
        <div class="search-form-item">
          <label>用户状态</label>
          <el-select
            v-model="searchForm.userStatus"
            placeholder="请选择用户状态"
            clearable
          >
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="待验证" :value="2" />
          </el-select>
        </div>
      </div>
      <div class="search-actions">
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><RefreshRight /></el-icon>
          重置
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="list-content">
      <div class="list-table" v-loading="loading">
        <div class="table-scroll-wrapper" ref="tableScroll">
          <el-table
            :data="userList"
            stripe
            style="width: 100%"
            :default-sort="{ prop: 'registerTime', order: 'descending' }"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="id" label="ID" width="80" align="center" />
            <el-table-column prop="username" label="用户名" min-width="120" show-overflow-tooltip />
            <el-table-column prop="nickname" label="昵称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="phone" label="手机号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
            <el-table-column prop="gender" label="性别" width="80" align="center">
              <template #default="{ row }">
                <span>{{ getGenderLabel(row.gender) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="birthDate" label="出生日期" min-width="120" show-overflow-tooltip />
            <el-table-column
              prop="userStatus"
              label="状态"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <el-tag :type="getUserStatusType(row.userStatus)">
                  {{ getUserStatusLabel(row.userStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="registerTime"
              label="注册时间"
              min-width="180"
              sortable
              show-overflow-tooltip
              :formatter="(row) => formatDateTime(row.registerTime)"
            />
            <el-table-column label="操作" min-width="220" align="center" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-button type="primary" size="small" @click="handleEdit(row)">
                    编辑
                  </el-button>
                  <el-button type="warning" size="small" @click="handleToggleStatus(row)">
                    {{ row.userStatus === 1 ? '禁用' : '启用' }}
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDelete(row)">
                    删除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 水平滑动进度条（当表格宽度超出容器时显示） -->
        <input
          v-show="showHScroll"
          ref="hSlider"
          class="horizontal-scroll"
          type="range"
          min="0"
          max="100"
          :value="hScrollPercent"
          @input="onSliderInput"
        />
      </div>
    </div>

    <!-- 分页 -->
    <div class="list-footer">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import UserDialog from './dialogs/UserDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, Plus } from '@element-plus/icons-vue'
import '@/assets/css/table-list.css'
import { getUserList, getUserById, addUser, updateUser, deleteUser, updateUserStatus } from '@/api/user'

// 搜索表单
const searchForm = reactive({
  username: '',
  phone: '',
  email: '',
  userStatus: ''
})

// 用户列表数据
const userList = ref([])

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('add') // 'add' or 'edit'
const editId = ref(null)
const editData = ref(null)

// Horizontal scroll controls
const tableScroll = ref(null)
const hScrollPercent = ref(0)
const showHScroll = ref(false)

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return 'N/A'
  return dateTime.replace('T', ' ').substring(0, 19)
}

// 获取性别标签
const getGenderLabel = (gender) => {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女'
  }
  return genderMap[gender] || '未知'
}

// 获取用户状态标签
const getUserStatusLabel = (status) => {
  const statusMap = {
    0: '禁用',
    1: '正常',
    2: '待验证'
  }
  return statusMap[status] || '未知'
}

// 获取用户状态标签类型
const getUserStatusType = (status) => {
  const typeMap = {
    0: 'danger',    // 禁用 - 红色
    1: 'success',   // 正常 - 绿色
    2: 'info'       // 待验证 - 蓝色
  }
  return typeMap[status] || 'info'
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      username: searchForm.username || undefined,
      phone: searchForm.phone || undefined,
      email: searchForm.email || undefined,
      userStatus: searchForm.userStatus !== '' ? searchForm.userStatus : undefined
    }
    const response = await getUserList(params)

    if (response.success) {
      // 后端数据结构：response.data.data 是用户数组，response.data.page/size/total 是分页信息
      userList.value = response.data.data || []
      pagination.total = response.data.total || 0
      pagination.currentPage = response.data.page || pagination.currentPage
      pagination.pageSize = response.data.size || pagination.pageSize
      // update horizontal scroll state after table data changes
      setTimeout(() => updateHScroll(), 50)
    } else {
      ElMessage.error(response.msg || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('网络异常，请稍后重试')
    console.error('获取用户列表失败：', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.username = ''
  searchForm.phone = ''
  searchForm.email = ''
  searchForm.userStatus = ''
  pagination.currentPage = 1
  fetchUserList()
}

// 新增用户
const handleAdd = () => {
  dialogMode.value = 'add'
  editId.value = null
  editData.value = null
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  dialogMode.value = 'edit'
  editId.value = row.id
  try {
    const res = await getUserById(row.id)
    if (res.success) {
      editData.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取用户信息失败')
    }
  } catch (e) {
    ElMessage.error('网络异常，获取用户信息失败')
  }
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  const newStatus = row.userStatus === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'

  try {
    await ElMessageBox.confirm(`确定要${statusText}该用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await updateUserStatus(row.id, newStatus)
    if (res.success) {
      ElMessage.success(`${statusText}成功`)
      fetchUserList()
    } else {
      ElMessage.error(res.msg || `${statusText}失败`)
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消操作')
    } else {
      ElMessage.error('操作失败，请稍后重试')
      console.error('状态切换失败：', error)
    }
  }
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteUser(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      fetchUserList()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败，请稍后重试')
      console.error('删除用户失败：', error)
    }
  }
}

// 弹窗提交成功回调
const handleDialogSuccess = async (formData) => {
  try {
    let res
    if (dialogMode.value === 'add') {
      res = await addUser(formData)
    } else {
      res = await updateUser(editId.value, formData)
    }
    
    if (res && res.success) {
      ElMessage.success(dialogMode.value === 'add' ? '添加成功' : '编辑成功')
      dialogVisible.value = false
      fetchUserList()
    } else {
      const errorMsg = res?.msg || '操作失败'
      ElMessage.error(errorMsg)
      console.error('操作返回失败:', res)
    }
  } catch (e) {
    ElMessage.error('网络异常，请稍后重试')
    console.error('操作失败：', e)
  }
}

// Horizontal scroll 处理函数
const updateHScroll = () => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  if (maxScroll > 0) {
    showHScroll.value = true
    hScrollPercent.value = Math.round((el.scrollLeft / maxScroll) * 100)
  } else {
    showHScroll.value = false
    hScrollPercent.value = 0
  }
}

const onTableScroll = () => {
  updateHScroll()
}

const onSliderInput = (e) => {
  const el = tableScroll.value
  if (!el) return
  const maxScroll = el.scrollWidth - el.clientWidth
  const percent = Number(e.target.value || 0)
  el.scrollLeft = Math.round((percent / 100) * maxScroll)
  hScrollPercent.value = percent
}

// 每页条数改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  fetchUserList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchUserList()
}

// 页面挂载时获取用户列表
onMounted(() => {
  fetchUserList()
  setTimeout(() => {
    if (tableScroll.value) {
      tableScroll.value.addEventListener('scroll', onTableScroll, { passive: true })
      updateHScroll()
    }
  }, 100)
  window.addEventListener('resize', updateHScroll)
})

onBeforeUnmount(() => {
  if (tableScroll.value) tableScroll.value.removeEventListener('scroll', onTableScroll)
  window.removeEventListener('resize', updateHScroll)
})
</script>